<template>
    <div class="app-container">
        <!-- 状态筛选 -->
        <el-radio-group v-model="queryParams.status" @change="handleQuery" style="margin-bottom: 10px;">
            <el-radio label="">全部</el-radio>
            <el-radio label="1">申请中</el-radio>
            <el-radio label="2">已完成</el-radio>
            <el-radio label="3">已关闭</el-radio>
        </el-radio-group>

        <!-- 搜索表单 -->
        <el-form :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="单据编号">
                <el-input v-model="queryParams.code" placeholder="请输入单据编号" clearable style="width: 220px" />
            </el-form-item>

            <el-form-item label="单据类别">
                <el-select v-model="queryParams.type" placeholder="请选择单据类别" clearable style="width: 220px">
                    <el-option label="请假" value="1" />
                    <el-option label="退住" value="2" />
                    <el-option label="入住" value="3" />
                </el-select>
            </el-form-item>

            <el-form-item label="申请时间">
                <el-date-picker v-model="queryParams.dateRange" type="daterange" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>

            <!-- 发起申请下拉框 -->
            <el-form-item label="发起申请">
                <el-select v-model="applyType" placeholder="请选择申请类别" clearable
                    style="width: 180px; margin-right: 10px;">
                    <el-option label="请假" value="1" />
                    <el-option label="退住" value="2" />
                    <el-option label="入住" value="3" />
                </el-select>
                <el-button type="success" @click="confirmApply">确认申请</el-button>
            </el-form-item>
        </el-form>

        <!-- 总数据提示 -->
        <div class="total-count" v-if="total > 0">共 {{ total }} 项数据</div>

        <!-- 任务表格 -->
        <el-table :data="taskList" v-loading="loading" style="width: 100%" border>
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="单据编号" prop="code" align="center" />
            <el-table-column label="单据标题" align="center">
                <template #default="scope">
                    {{ formatTitle(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column label="单据类别" align="center">
                <template #default="scope">
                    {{ formatType(scope.row.type) }}
                </template>
            </el-table-column>
            <el-table-column label="申请人" prop="applicat" align="center" />
            <el-table-column label="申请时间" align="center">
                <template #default="scope">
                    {{ formatTime(scope.row.applicationTime) }}
                </template>
            </el-table-column>
            <el-table-column label="完成时间" align="center">
                <template #default="scope">
                    {{ formatTime(scope.row.finishTime) }}
                </template>
            </el-table-column>
            <el-table-column label="流程状态" align="center">
                <template #default="scope">
                    <el-tag :type="statusType(scope.row.status)">
                        {{ formatStatus(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
                    <el-button type="danger" size="small" @click="handleRevoke(scope.row)"
                        v-if="scope.row.status === 1">
                        撤销
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-if="total > 0" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize"
            :total="total" layout="sizes, prev, pager, next, jumper, ->, total" :page-sizes="[5, 10, 20, 50]"
            @current-change="handlePageChange" @size-change="handleSizeChange" />

        <!-- 撤销确认弹窗 -->
        <el-dialog title="确认撤销" v-model:visible="revokeDialogVisible" width="30%" append-to-body>
            <p>确定要撤销【{{ currentRevokeRow?.code || '' }}】这条申请吗？撤销后将无法恢复。</p>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="revokeDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmRevoke">确认撤销</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { postPendingTasks, postRevoke } from '@/api/myApplyList/myApplyList'
import router from '@/router'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 状态管理
const loading = ref(false)
const taskList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
    code: '',
    type: null,
    status: '', // 初始为空（全部）
    dateRange: [],
    pageNum: 1,
    pageSize: 10,
    reqType: 1
})

// 申请类别选择（下拉框）
const applyType = ref(null)

// 撤销相关
const revokeDialogVisible = ref(false)
const currentRevokeRow = ref(null)

// 获取列表（修复“全部”选项空指针问题）
function getList() {
    loading.value = true
    const params = {
        ...queryParams,
        startTime: queryParams.dateRange[0] ? new Date(queryParams.dateRange[0]) : null,
        endTime: queryParams.dateRange[1] ? new Date(queryParams.dateRange[1]) : null,
        type: queryParams.type ? parseInt(queryParams.type) : null,
        reqType:1
    }

    // 如果 status 是空或非有效数字，则不传
    if (queryParams.status && queryParams.status !== '') {
        params.status = parseInt(queryParams.status)
    } else {
        delete params.status
    }

    postPendingTasks(params)
        .then(res => {
            if (res.code !== 200) throw new Error(res.msg || '请求失败')
            taskList.value = res.data || []
            total.value = res.data.total || 0
            loading.value = false
        })
        .catch(err => {
            console.error('获取列表失败：', err)
            loading.value = false
            ElMessage.error('获取数据失败，请重试')
        })
}

// 搜索
function handleQuery() {
    queryParams.pageNum = 1
    getList()
}

// 重置
function resetQuery() {
    queryParams.code = ''
    queryParams.type = null
    queryParams.status = '' // 重置为“全部”
    queryParams.dateRange = []
    handleQuery()
}

// 分页
function handlePageChange(page) {
    queryParams.pageNum = page
    getList()
}

function handleSizeChange(size) {
    queryParams.pageSize = size
    queryParams.pageNum = 1
    getList()
}

// 格式化工具函数
function formatType(type) {
    const typeMap = { 1: '请假', 2: '退住', 3: '入住' }
    return typeMap[type] || '未知'
}

function formatStatus(status) {
    const statusMap = { 1: '申请中', 2: '已完成', 3: '已关闭' }
    return statusMap[status] || '未知'
}

function statusType(status) {
    const typeMap = { 1: 'warning', 2: 'success', 3: 'danger' }
    return typeMap[status] || 'info'
}

function formatTime(time) {
    if (!time) return '——'
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

function formatTitle(row) {
    if (row.title) return row.title
    const typeMap = { 1: '请假', 2: '退住', 3: '入住' }
    return `${row.applicat || '未知申请人'}的${typeMap[row.type] || '未知'}申请`
}

// 查看详情
function handleView(row) {
    router.push(`/applications/detail/${row.id}?type=${row.type}`)
}

// 撤销操作
function handleRevoke(row) {
    currentRevokeRow.value = row
    revokeDialogVisible.value = true
}

function confirmRevoke() {
    if (!currentRevokeRow.value?.id) {
        revokeDialogVisible.value = false
        return
    }

    postRevoke({ taskId: currentRevokeRow.value.id })
        .then(res => {
            if (res.code !== 200) throw new Error(res.msg || '撤销失败')
            ElMessage.success('撤销成功')
            revokeDialogVisible.value = false
            getList()
        })
        .catch(err => {
            console.error('撤销失败：', err)
            ElMessage.error('撤销失败，请重试')
            revokeDialogVisible.value = false
        })
}

// 发起申请（下拉框确认后跳转）
function confirmApply() {
    if (!applyType.value) {
        ElMessage.warning('请选择申请类别')
        return
    }

    switch (Number(applyType.value)){
        case 1: // 请假
            router.push('/residing/leaveRequestManager/leaveRequest')
            break
        case 2: // 退住
            router.push('/CollaborationWork/MyApply/CheckoutApply')
            break
        case 3: // 入住
            router.push('/CollaborationWork/MyApply/CheckInApply')
            break
        default:
            ElMessage.warning('未知申请类别')
            break
    }

    applyType.value = null
}

// 页面加载时获取列表
onMounted(() => {
    getList()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.el-form-item {
    margin-right: 20px;
    margin-bottom: 15px;
}

.total-count {
    margin: 10px 0;
    font-size: 14px;
    color: #606266;
}

.el-table {
    margin-bottom: 15px;
}

.dialog-footer {
    text-align: right;
}

:deep(.el-radio-group) {
    padding: 10px 0;
}
</style>
